package com.wanxin.contoroller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("userLogin")
public class MyController {

    @GetMapping("/login/{user}/{pwd}")
    public String userLogin(@PathVariable("user")String user, @PathVariable("pwd")String pwd){
        //获取SecurityManager对象
        Factory<SecurityManager> factory= new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        //获取Subject对象
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        //调用登入认证方法
         // 创建对象存储认证信息
        AuthenticationToken token=new UsernamePasswordToken(user,pwd);
         //完成登入验证
        try {
            subject.login(token);
            //授权认证
             //角色判断
            boolean role1 = subject.hasRole("role1");
            System.out.println("判断是否具有角色："+role1);
             //权限判断
            //subject.checkPermission("sys:user:insert");//权限判断，没有返回值
            boolean permitted = subject.isPermitted("sys:user:insert");//权限判断，有返回值
            System.out.println("权限判断结果"+permitted);
            return "成功";
        } catch (UnknownAccountException e) {
            return "账号不存在";
        }catch (IncorrectCredentialsException e) {
            return "密码错误";
        }catch (AuthenticationException e) {
            e.printStackTrace();
            return "权限不足";
        }

    }

    @GetMapping("/userSq")
    public String userSq(){
        Subject subject = SecurityUtils.getSubject();
        boolean role1 = subject.hasRole("role1");
        System.out.println("判断是否具有角色："+role1);
        boolean permitted = subject.isPermitted("sys:user:insert");//权限判断，没有返回值
        System.out.println("权限判断结果"+permitted);//权限判断，有返回值
        return "授权的角色判断结果："+role1+"权限判断结果："+permitted;
    }

}
